"use client";

import { AdSidebar } from "@/components/ad-sidebar";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Heart,
  Eye,
  ExternalLink,
  AlertCircle,
  ThumbsUp,
  MessageCircle,
  Star,
} from "lucide-react";
import Image from "next/image";
import { useEffect, useState, useMemo, Suspense } from "react";
import { useRouter } from "next/navigation";
import { Content } from "@/types/content";
import { getContentDetail, viewContent, listContents } from "@/apis/client/content";
import { toast } from "sonner";
import { getFavoriteStatus, toggleFavorite } from "@/apis/client/favorite";
import { createChatSession } from "@/apis/client/chat";
import { useAuth } from "@/lib/auth-context";
import { useMenu } from "@/contexts/MenuContext";
import { Skeleton } from "@/components/ui/skeleton";
import { ContentTypeEnum } from "@/constants";
import { useSearchParams } from "next/navigation";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { pickDefaultIconForKey } from "@/constants/default-icons";
import { ToolCard } from "@/components/tool-card";

// 将使用 useSearchParams 的逻辑提取到单独的组件中
function ContentDetailContent() {
  const router = useRouter();
  const { user } = useAuth();
  const queryClient = useQueryClient();

  const searchParams = useSearchParams();
  const id = searchParams.get("id");

  const stripHtml = (html: string) =>
    html.replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim();

  // 使用 useQuery 缓存内容详情数据
  const { data: tool, isLoading: isContentLoading } = useQuery({
    queryKey: ["contentDetail", id],
    queryFn: () => getContentDetail(id!),
    enabled: !!id, // 只有当 id 存在时才执行查询
    staleTime: 5 * 60 * 1000, // 5分钟内数据被认为是新鲜的
    gcTime: 10 * 60 * 1000, // 10分钟后清除缓存
  });

  // 使用 useQuery 缓存收藏状态数据
  const { data: favoriteData } = useQuery({
    queryKey: ["favoriteStatus", tool?.id],
    queryFn: () => getFavoriteStatus(tool!.id),
    enabled: !!user && !!tool?.id, // 只有当用户登录且内容存在时才执行查询
    staleTime: 2 * 60 * 1000, // 2分钟内数据被认为是新鲜的
    gcTime: 5 * 60 * 1000, // 5分钟后清除缓存
  });

  const isFavorited = favoriteData?.isFavorited || false;

  // 根据同分类获取“类似网站”
  const categoryId = tool?.categories?.[0]?.id;
  const { data: similarPage, isLoading: isSimilarLoading } = useQuery({
    queryKey: ["similarContents", categoryId],
    queryFn: () => listContents({ page: 1, pageSize: 9, categoryId }),
    enabled: !!categoryId,
    staleTime: 60 * 1000,
    gcTime: 5 * 60 * 1000,
  });
  const similarRecords = useMemo(
    () => (similarPage?.records || []).filter((c) => c.id !== tool?.id),
    [similarPage?.records, tool?.id]
  );

  // 当内容加载完成后，增加浏览量
  useEffect(() => {
    if (tool) {
      viewContent(tool.id);
    }
  }, [tool]);

  const handleFavorite = async () => {
    if (!user) {
      toast.error("Please sign in to favorite");
      return;
    }
    if (!tool) return;

    try {
      await toggleFavorite(tool.id);
      // 更新缓存中的收藏状态
      queryClient.setQueryData(["favoriteStatus", tool.id], {
        isFavorited: !isFavorited,
      });
      toast.success(isFavorited ? "Unfavorited" : "Favorited");
    } catch (error) {
      toast.error("Failed to update favorite status");
    }
  };

  const handleLinkDirect = async () => {
    if (!tool) return;

    if (tool.type === ContentTypeEnum.TOOL) {
      const newChatId = `chat_${Date.now()}_${Math.random()
        .toString(36)
        .substring(2, 11)}`;
      router.push(`/chat?chatId=${newChatId}&contentId=${tool.id}`);
    } else if (tool.url) {
      window.open(tool.url, "_blank");
    }
  };

  if (isContentLoading || !tool) {
    return (
      <main className="flex-1 bg-background">
        <div className="container mx-auto px-4 py-6 max-w-7xl">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <div className="lg:col-span-2">
              <div className="flex flex-col md:flex-row gap-6 mb-6">
                <Card className="p-4 bg-muted/30 md:w-[380px] flex-shrink-0">
                  <Skeleton className="aspect-video w-full rounded-lg mb-3 bg-gray-200" />
                  <div className="flex items-center justify-center gap-8 text-sm text-muted-foreground pt-2 border-t">
                    <div className="flex items-center gap-1.5">
                      <Skeleton className="w-4 h-4 bg-gray-200" />
                      <Skeleton className="w-8 h-4 bg-gray-200" />
                    </div>
                    <div className="flex items-center gap-1.5">
                      <Skeleton className="w-4 h-4 bg-gray-200" />
                      <Skeleton className="w-8 h-4 bg-gray-200" />
                    </div>
                  </div>
                </Card>
                <div className="flex-1 space-y-4">
                  <Skeleton className="h-6 w-1/4 bg-gray-200" />
                  <Skeleton className="h-8 w-3/4 bg-gray-200" />
                  <Skeleton className="h-20 w-full bg-gray-200" />
                  <div className="flex gap-3 pt-2">
                    <Skeleton className="h-10 w-32 bg-gray-200" />
                    <Skeleton className="h-10 w-10 bg-gray-200" />
                  </div>
                </div>
              </div>
            </div>
            <div className="lg:col-span-1">
              <AdSidebar />
            </div>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="flex-1 bg-background">
      <div className="container mx-auto px-4 py-6 max-w-7xl">
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Main Content */}
          <div className="lg:col-span-2">
            <div className="flex flex-col md:flex-row gap-6 mb-6">
              {/* Tool Preview Card - Smaller and on the left */}
              <Card className="p-4 bg-muted/30 md:w-[380px] flex-shrink-0">
                <div className="aspect-video rounded-lg overflow-hidden mb-3 flex items-center justify-center">
                  <Image
                    src={tool.cover?.url || pickDefaultIconForKey(tool.title)}
                    alt={tool.title}
                    width={350}
                    height={200}
                    className="object-contain"
                    style={{
                      objectFit: "contain",
                      height:'100%'
                    }}
                  />
                </div>

                <div className="flex items-center justify-center gap-8 text-sm text-muted-foreground pt-2 border-t">
                  <div className="flex items-center gap-1.5">
                    <Heart className="w-4 h-4" />
                    <span>{tool.favoritesCount || 0}</span>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <Eye className="w-4 h-4" />
                    <span>{tool.viewCount || 0}</span>
                  </div>
                </div>
              </Card>

              {/* Tool Info - On the right */}
              <div className="flex-1 space-y-4 flex flex-col justify-between">
                <div>
                  <div className="flex gap-2 mb-4">
                    {tool.categories && tool.categories.length > 0 && (
                      <Badge className="bg-primary text-primary-foreground">
                        {tool.categories[0].name}
                      </Badge>
                    )}
                  </div>

                  <h1 className="text-2xl font-bold text-foreground">
                    {tool.title}
                  </h1>
                  {/* 简述 */}
                  <p className="text-muted-foreground leading-relaxed mt-2">
                    {tool.summary || (tool.content ? stripHtml(tool.content).slice(0, 120) : "")}
                  </p>
                </div>

                {/* 网站描述内容移至下方“网站描述”模块 ，这里显示简述*/}

                {/* Action Buttons */}
                <div className="flex gap-3 pt-2">
                  <Button
                    onClick={handleLinkDirect}
                    variant="outline"
                    className="gap-2 w-full bg-transparent flex-1 max-w-[160px]"
                  >
                    链接直达
                    <ExternalLink className="w-4 h-4" />
                  </Button>
                  <Button
                    onClick={handleFavorite}
                    className={`${
                      isFavorited ? "bg-red-500 hover:bg-red-600" : ""
                    } gap-2`}
                  >
                    <Heart className="w-4 h-4" />
                  </Button>
                </div>
              </div>
            </div>
            {/* 网站描述 */}
            <div className="space-y-4">
              <div className="flex items-center gap-2 pb-2 border-l-4 border-primary pl-3">
                <h2 className="text-lg font-medium text-foreground">
                  网站描述
                </h2>
              </div>

              {/* 描述内容卡片 */}
              <Card className="p-4 bg-muted/30">
                <div
                  className="text-muted-foreground leading-relaxed"
                  dangerouslySetInnerHTML={{ __html: tool.content }}
                />
              </Card>

              {/* 版权声明 */}
              <Card className="p-4 bg-yellow-50 border-yellow-200">
                <div className="flex gap-2 text-sm text-yellow-800">
                  <AlertCircle className="w-5 h-5 flex-shrink-0 mt-0.5" />
                  <p className="leading-relaxed">
                    版权声明：非特殊说明，本站AI导航网上的内容均由本站作者及会员发布，原作品版权归原作者，本站只做收藏展示。
                  </p>
                </div>
              </Card>
            </div>

            {/* Similar Websites */}
            <div className="mt-8">
              <div className="flex items-center gap-2 mb-4 pb-2 border-l-4 border-primary pl-3">
                <h2 className="text-lg font-medium text-foreground">
                  类似网站
                </h2>
              </div>
              {isSimilarLoading ? (
                <div className="text-sm text-muted-foreground">正在加载类似网站...</div>
              ) : similarRecords.length === 0 ? (
                <div className="text-sm text-muted-foreground">暂无类似网站推荐</div>
              ) : (
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                  {similarRecords.map((c) => (
                    <ToolCard
                      key={c.id}
                      id={c.id}
                      name={c.title}
                      summary={c.summary || ""}
                      description={c.content || ""}
                      icon={c.cover?.url || ""}
                      viewCount={c.viewCount}
                      favoritesCount={c.favoritesCount}
                    />
                  ))}
                </div>
              )}
            </div>
          </div>

          {/* Right Sidebar - Advertisement */}
          <div className="lg:col-span-1">
            <AdSidebar />
          </div>
        </div>
      </div>
    </main>
  );
}

// 主页面组件，用 Suspense 包裹使用 useSearchParams 的组件
export default function ContentDetailPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-background">
          <main className="container mx-auto px-4 py-8">
            <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
              <div className="lg:col-span-3">
                <Card className="p-6">
                  <div className="space-y-4">
                    <Skeleton className="h-8 w-3/4" />
                    <Skeleton className="h-4 w-full" />
                    <Skeleton className="h-4 w-2/3" />
                    <Skeleton className="h-64 w-full" />
                  </div>
                </Card>
              </div>
              <div className="lg:col-span-1">
                <Skeleton className="h-96 w-full" />
              </div>
            </div>
          </main>
        </div>
      }
    >
      <ContentDetailContent />
    </Suspense>
  );
}
